package com.zr.controller;

import com.zr.controller.R.Code;
import com.zr.controller.R.Result;
import com.zr.pojo.User;
import com.zr.service.UserService;
import com.zr.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
@CrossOrigin
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/reguser")
    public Result regUser( User user){
//        System.out.println("in reg...");
        Boolean flag = userService.regUser(user);
        return new Result(flag?Code.SAVE_OK:Code.SAVE_ERR,null ,flag?"注册成功，请登录！":"注册失败,用户名已被占用！");
    }

    @PostMapping("/login")
    public Result login(User user){
//        System.out.println("in login...");
        Boolean flag = userService.login(user);
        Result result = new Result(flag ? Code.GET_OK : Code.GET_ERR, null, flag ? "登录成功" : "登录失败");
//        给响应对象result设置token属性值
       if(flag){
           result.setToken(JwtUtils.createToken(user.getUsername(), user.getNickname()));
       }
        return result;
    }
}
